package com.webber.demo.common.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.springframework.cglib.beans.BeanMap;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * @ClassName: InvokeUtil反射工具类
 * @Description: 利用反射，转换map和javaBean 
 * @since 2017-07-28
 * @author JobsZhang
 *
 */

public class InvokeUtil {
	
	//用来遍历对象属性和属性值
	public static Map<String,String> readClassAttr(Object tb) throws Exception{
	  Field[] fields=tb.getClass().getDeclaredFields();
	  String keyList="";
	  String valueList="";
	  for(Field field:fields){
	   field.setAccessible(true);  //实体属性为private，此处必须写上
	   if(field.get(tb)!=null&&!"".equals(field.get(tb).toString())){   
	    keyList+=","+field.getName();
	    if("a".equals(field.getName())){
	     valueList+=","+"特殊格式哦";
	    }else{
	     valueList+=","+field.get(tb);
	    }
	    ///System.out.println(field.getName()+"   "+field.get(tb).toString());
	   }
	  }
	  Map<String,String> maps=new HashMap<String, String>();
	  maps.put("keys", keyList);
	  maps.put("values",valueList);
	  return maps;
	}
	 /**
     * JavaBean对象转化成Map对象
     * 
     * @param javaBean
     * @return
     * @author jqlin
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map Bean2Map(Object javaBean) {
        Map map = new HashMap();
        try {
            // 获取javaBean属性
            BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());

            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            if (propertyDescriptors != null && propertyDescriptors.length > 0) {
                String propertyName = null; // javaBean属性名
                Object propertyValue = null; // javaBean属性值
                for (PropertyDescriptor pd : propertyDescriptors) {
                    propertyName = pd.getName();
                    if (!propertyName.equals("class")) {
                        Method readMethod = pd.getReadMethod();
                        propertyValue = readMethod.invoke(javaBean, new Object[0]);
                        map.put(propertyName, propertyValue);
                    }
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }  
        
        return map;
    }
    /**
     * 
     * @Title: setMethodValue 
     * @Description: 调用object的set方法，对obj的属性赋值
     * @since 2017-07-28
     * @param obj
     * @param method
     * @param objects
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException void
     */
    private static void setMethodValue(Object obj, Method method, Object objects) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        if (Timestamp.class.getName().equals(method.getParameterTypes()[0].getName())) {
            if (null != objects && !"null".equals(objects)) {
            	if(DateUtil.isTimeLegal(objects.toString().trim())) {
            		method.invoke(obj, DateUtil.String2Timestamp(objects.toString(),DateUtil.YYYY_MM_DD_HH_MM_SS_PATTERN)  );
            	}
            	if(DateUtil.isDateLegal(objects.toString().trim())) {
            		String time = objects.toString();
            		Timestamp ts = DateUtil.String2Timestamp(time,DateUtil.YYYY_MM_DD_PATTERN);
            		method.invoke(obj, ts);
            	}
                
            }
        } else if (Date.class.getName().equals(method.getParameterTypes()[0].getName())) {
            if (null != objects && !"null".equals(objects)) {
            	Timestamp time = new Timestamp((long) objects);
            	
                method.invoke(obj, time);
            }
        } else if (java.sql.Date.class.getName().equals(method.getParameterTypes()[0].getName())) {
            if (null != objects && !"null".equals(objects)) {
                method.invoke(obj, new Timestamp((long) objects));
            }
        } else {
            method.invoke(obj, objects);
        }
    }

    /**
     * 
     * @Title: convertMap 
     * @Description: 将一个 Map 对象转化为一个 JavaBean
     * @since 2017-07-28
     * @param type
     * @param map
     * @throws IntrospectionException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws InvocationTargetException T
     */
    @SuppressWarnings("rawtypes")
    public static <T> T convertMap(Class<T> type, Map map) throws IntrospectionException, IllegalAccessException, InstantiationException, InvocationTargetException {
        BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
        T instance = type.newInstance(); // 创建 JavaBean 对象

        // 给 JavaBean 对象的属性赋值
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();

            if (map.containsKey(propertyName)) {
                // 下面的 try起来，这样当一个属性赋值失败的时候就不会影响其他属性赋值。
                Object value = map.get(propertyName);

                Object[] args = new Object[1];
                args[0] = value;

                setMethodValue(instance, descriptor.getWriteMethod(), value);
            }
        }
        return instance;
    }
    /** 
     * 将List<T>转换为List<Map<String, Object>> 
     * @param objList 
     * @return 
     * @throws JsonGenerationException 
     * @throws JsonMappingException 
     * @throws IOException 
     */  
    public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {  
        List<Map<String, Object>> list = Lists.newArrayList();  
        if (objList != null && objList.size() > 0) {  
            Map<String, Object> map = null;  
            T bean = null;  
            for (int i = 0,size = objList.size(); i < size; i++) {  
                bean = objList.get(i);  
                map = beanToMap(bean);  
                list.add(map);  
            }  
        }  
        return list;  
    } 
    /** 
     * 将List<Map<String,Object>>转换为List<T> 
     * @param maps 
     * @param clazz 
     * @return 
     * @throws InstantiationException 
     * @throws IllegalAccessException 
     */  
    public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps,Class<T> clazz) throws InstantiationException, IllegalAccessException {  
        List<T> list = Lists.newArrayList();  
        if (maps != null && maps.size() > 0) {  
            Map<String, Object> map = null;  
            T bean = null;  
            for (int i = 0,size = maps.size(); i < size; i++) {  
                map = maps.get(i);  
                bean = clazz.newInstance();  
                mapToBean(map, bean);  
                list.add(bean);  
            }  
        }  
        return list;  
    }
    /** 
     * 将map装换为javabean对象 
     * @param map 
     * @param bean 
     * @return 
     */  
    public static <T> T mapToBean(Map<String, Object> map,T bean) {  
        BeanMap beanMap = BeanMap.create(bean);  
        beanMap.putAll(map);  
        return bean;  
    } 
    /**
    * 将对象装换为map 
    * @param bean 
    * @return 
    */  
   public static <T> Map<String, Object> beanToMap(T bean) {  
       Map<String, Object> map = Maps.newHashMap();  
       if (bean != null) {  
           BeanMap beanMap = BeanMap.create(bean);  
           for (Object key : beanMap.keySet()) {  
               map.put(key+"", beanMap.get(key));  
           }             
       }  
       return map;  
   }  
}